package biznussoft.metercor.fragments;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import biznussoft.metercor.MainActivity;
import biznussoft.metercor.R;
import biznussoft.metercor.entity.AccountModel;
import biznussoft.metercor.entity.StockTransferLineModel;
import biznussoft.metercor.entity.StockTransferModel;
import biznussoft.metercor.listener.Globallistener;
import biznussoft.metercor.utils.CustomProgressDialog;
import biznussoft.metercor.utils.Session;

import com.google.gson.Gson;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class StockTransferFragment  extends Fragment implements OnItemClickListener{

	private Dialog progressDialog; 
	private RestClient client;
	private ArrayList<StockTransferLineModel> contactsList;
	public static ArrayList<StockTransferModel> list;
	public static ArrayList<StockTransferModel> sitelist;
	public static HashMap<String, ArrayList<StockTransferLineModel>> subContactsList;
	private Globallistener mHomeItemListener;        
	private ListView lv;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.service_order_records, null);                  
	}         


	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mHomeItemListener = (Globallistener) (activity);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.listview);
		lv.setOnItemClickListener(this);      
		client =  MainActivity.mActivity.client;
		AccountModel.api_Version = getString(R.string.api_version);



	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		super.onCreateOptionsMenu(menu, inflater);
		MenuItem mytrack = menu.add("Stock Transfer");
		MenuItemCompat.setShowAsAction(mytrack, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		mytrack.setIcon(R.drawable.add); 

	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		if(item.getTitle().equals("Stock Transfer")){
			NewStockTransferFragment fragment = new NewStockTransferFragment();
			FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
			transaction.replace(R.id.stock, fragment);                            
			transaction.commit();
			}
		return super.onOptionsItemSelected(item);
	}

	public void retriveLeads()                            
	{
		try{
			progressDialog = CustomProgressDialog
					.getInstance().createProgressDialog(getActivity());                 
			progressDialog.setCanceledOnTouchOutside(false);
			progressDialog.show();

			String accounts = "Select id,Name,Destination_Location__c,Source_Location__c,FConnect__Source_Location__c,FConnect__Destination_Location__c,FConnect__Additional_Information__c,(Select Item_Name__c,Id,Name,FConnect__Inventory_No__c,FConnect__Item__c,FConnect__Serial_ID__c,FConnect__Lot_ID__c,FConnect__Qty_Transferred__c,FConnect__Posted_To_Inventory__c,FConnect__Request_Date__c from FConnect__Stock_Transfer_Lines__r) from FConnect__Stock_Transfer__c";


			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {      
						progressDialog.dismiss();
						Log.i("NCS","FConnect__Stock_Transfer__c  is  :"+result.toString());
						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						list = new ArrayList<StockTransferModel>();
						subContactsList = new HashMap<String, ArrayList<StockTransferLineModel>>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							contactsList = new ArrayList<StockTransferLineModel>();
							if(!jsonArray.isNull(i)){
								StockTransferModel bean = _gson.fromJson(jsonArray.getString(i), StockTransferModel.class);
								String ID = jsonArray.getJSONObject(i).getString("Id");
								list.add(bean);
								try{
									JSONObject contacts = jsonArray.getJSONObject(i).getJSONObject("FConnect__Stock_Transfer_Lines__r");
									JSONArray contactsArray = contacts.getJSONArray("records");

									Gson contactsList_gson = new Gson();
									for(int j=0; j< contactsArray.length(); j++)
									{
										if(!contactsArray.isNull(j)){
											StockTransferLineModel contactbean = contactsList_gson.fromJson(contactsArray.getString(j), StockTransferLineModel.class);
											contactsList.add(contactbean);


										}
									}

									subContactsList.put(ID, contactsList);


								}catch(Exception e){
									Log.i("NCS","Contacts Exception   is  :"+e.getMessage());
								}
							}
						}

						showRecords();

					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}

		try{

			String accounts = "Select id,Name from FConnect__Site__c";


			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {      
						Log.i("NCS","RestResponse  is  :"+result.toString());
						JSONObject jsonObject1 = new JSONObject(result.asString());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");

						sitelist = new ArrayList<StockTransferModel>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								StockTransferModel bean = _gson.fromJson(jsonArray.getString(i), StockTransferModel.class);
								String ID = jsonArray.getJSONObject(i).getString("Id");
								sitelist.add(bean);

							}
						}



					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}

	}
	class ListComparator implements Comparator<StockTransferModel>,Serializable
	{
		public int compare(StockTransferModel o1, StockTransferModel o2)
		{

			return o1.getName().compareTo(o2.getName());

		}

	}

	public void showRecords(){
		Collections.sort(list, new ListComparator());
		StockTransferAdapter adapter = new StockTransferAdapter(getActivity(), list);
		lv.setAdapter(adapter);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		setHasOptionsMenu(false);
		mHomeItemListener.getResponse(position);

		StockTransferModel model  = list.get(position);
		Session.sSource = model.getSourceLocation();
	}
	class StockTransferAdapter extends BaseAdapter {
		boolean checkArray[]; 	
		ArrayList<StockTransferModel> listdata;
		Context mContext;

		public StockTransferAdapter(Context context, ArrayList<StockTransferModel> list) {
			// TODO Auto-generated constructor stub
			this.listdata = list;
			this.mContext = context;
			checkArray = new boolean[list.size()];
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return listdata.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public class ViewHolder{
			public TextView name;    
			public TextView phno;
			//		public TextView billingCity;
			public RelativeLayout rLayout;
			public ImageView image;
		}

		public View getView(final int position, View v, ViewGroup parent) {
			// TODO Auto-generated method stub

			ViewHolder holder;

			if(v == null){

				holder = new ViewHolder();
				LayoutInflater inflator = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = inflator.inflate(R.layout.common_details_page, null);
				holder.name  = (TextView) v.findViewById(R.id.text1);
				//			holder.billingCity  = (TextView) v.findViewById(R.id.text2);
				holder.phno = (TextView) v.findViewById(R.id.text2);
				holder.image = (ImageView) v.findViewById(R.id.imageview);
				holder.rLayout  = (RelativeLayout) v.findViewById(R.id.rrlayout_1);
				v.setTag(holder);
			}else{
				holder = (ViewHolder) v.getTag();
				holder.image.setImageResource(R.drawable.inventory_icon);
			}

			 v.setTag(holder);
		      holder.rLayout.setId(position);
			
			final StockTransferModel bean = listdata.get(position);

			holder.name.setText(bean.getName());
			holder.phno.setText(bean.getSourceName()+" || "+bean.getDestinationName());
			//holder.image.setImageResource(R.drawable.inventory_icon);
			
			
			holder.rLayout.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					setHasOptionsMenu(false);
					mHomeItemListener.getResponse(position);
					Session.sStockTransfer = bean.getName();              
					Session.sStockTransferId = bean.getId();
					Session.sSource = bean.getSourceLocation();
					for (int i = 0; i <listdata.size(); i++) {
	                    if (v.getId() == i) {
	                    	checkArray[i] = true;
	                    } else {
	                    	checkArray[i] = false;
	                    }
	                }
	                notifyDataSetChanged();
	            }
				
			});           
			
			if (checkArray[position]) {
	            holder.image.setImageResource(R.drawable.inventory_icon_active);
	        } else {
	            holder.image.setImageResource(R.drawable.inventory_icon);
	        }
			

			return v;
		}

	}


}

